<template>
  <el-dialog
    title="批量导入"
    :close-on-click-modal="false"
    :visible.sync="visible"
    class="jsbos-dialog jsbos-dialog_center jsbos-dialog-import"
    lock-scroll
    width="95%"
  >
    <el-steps :active="active" align-center>
      <el-step title="上传文件"></el-step>
      <el-step title="数据预览"></el-step>
      <el-step title="导入数据"></el-step>
    </el-steps>
    <div class="import-main" v-show="active == 1">
      <div class="upload">
        <div class="up_left">
          <img src="@/assets/images/upload.png" />
        </div>
        <div class="up_right">
          <p class="title">上传填好的数据表</p>
          <p class="tip">
            文件后缀名必须是xls或xlsx，文件大小不超过500KB，最多支持导入1000条数据
          </p>
          <!-- :action="define.comUrl + '/api/extend/Employee/Uploader'" -->
          <el-upload
            :action="define.comUrl + '/api/extend/Employee/Uploader'"
            :headers="{ Authorization: $store.getters.token }"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-change="handleChange"
            :file-list="fileList"
            accept=".xls,.xlsx"
            :before-upload="beforeUpload"
            class="upload-area"
          >
            <el-button type="text">上传文件</el-button>
          </el-upload>
        </div>
      </div>
      <div class="upload">
        <div class="up_left">
          <img src="@/assets/images/import.png" />
        </div>
        <div class="up_right">
          <p class="title">填写导入数据信息</p>
          <p class="tip">
            请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除
          </p>
          <el-button type="text" @click="templateDownload">下载模板</el-button>
        </div>
      </div>
    </div>
    <div class="import-main" v-show="active == 2">
      <jsbos-table v-loading="listLoading" :data="list">
        <el-table-column prop="title" label="题目">
          <template slot-scope="scope">
            <el-input v-model="scope.row.title" />
          </template>
        </el-table-column>
        <el-table-column prop="questionType" label="题目类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.questionType">
              <el-option label="单选题" value="单选题"></el-option>
              <el-option label="多选题" value="多选题"></el-option>
              <el-option label="判断题" value="判断题"></el-option>
              <el-option label="填空题" value="填空题"></el-option>
              <el-option label="问答题" value="问答题"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="analysis" label="答案解析">
          <template slot-scope="scope">
            <el-input v-model="scope.row.analysis" />
          </template>
        </el-table-column>
        <el-table-column prop="difficultyGrade" label="试题等级">
          <template slot-scope="scope">
            <el-select v-model="scope.row.difficultyGrade">
              <el-option label="简单" value="简单"></el-option>
              <el-option label="中等" value="中等"></el-option>
              <el-option label="困难" value="困难"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="answer" label="答案">
          <template slot-scope="scope">
            <el-input v-model="scope.row.answer" />
          </template>
        </el-table-column>
        <el-table-column prop="option1" label="选项1">
          <template slot-scope="scope">
            <el-input v-model="scope.row.option1" />
          </template>
        </el-table-column>
        <el-table-column prop="option2" label="选项2">
          <template slot-scope="scope">
            <el-input v-model="scope.row.option2" />
          </template>
        </el-table-column>
        <el-table-column prop="option3" label="选项3">
          <template slot-scope="scope">
            <el-input v-model="scope.row.option3" />
          </template>
        </el-table-column>
        <el-table-column prop="option4" label="选项4">
          <template slot-scope="scope">
            <el-input v-model="scope.row.option4" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="选项" width="300">
          <template slot-scope="scope">
            <div v-if="isChoiceQuestion(scope.row.questionType)" class="options-container">
              <div v-for="i in 10" :key="i" class="option-item" v-if="scope.row[`option${i}`]">
                <span class="option-label">选项{{i}}:</span>
                <el-input v-model="scope.row[`option${i}`]" size="small" />
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" fixed="right" width="50">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              class="jsbos-table-delBtn"
              @click="handleDel(scope.$index)"
              >删除</el-button>
          </template>
        </el-table-column>
      </jsbos-table>
    </div>
    <div class="import-main" v-show="active == 3">
      <div class="success" v-if="!result.resultType">
        <img src="@/assets/images/success.png" alt="" />
        <p class="success-title">批量导入成功</p>
        <p class="success-tip">您已成功导入{{ result.snum }}条数据</p>
      </div>
      <div class="unsuccess" v-if="result.resultType">
        <el-alert
          title="错误提醒：导入失败数据展示"
          type="warning"
          show-icon
          :closable="false"
        />
        <div class="upload error-show">
          <div class="up_left">
            <img class="" src="@/assets/images/tip.png" />
          </div>
          <div class="up_right">
            <p class="tip">
              正常数量条数：<el-link type="success" :underline="false"
                >{{ result.snum }}条
              </el-link>
            </p>
            <p class="tip">
              异常数量条数：<el-link type="danger" :underline="false"
                >{{ result.fnum }}条
              </el-link>
            </p>
          </div>
        </div>
        <p class="contips">
          以下文件数据为导入异常数据<el-button
            type="error"
            plain
            size="mini"
            @click.stop.prevent="exportData"
            >导出</el-button>
        </p>
        <jsbos-table id="exportTable" :data="resultList" height="280px">
          <el-table-column prop="title" label="题目" />
          <el-table-column prop="questionType" label="题目类型" />
          <el-table-column prop="answer" label="答案" />
          <el-table-column prop="difficultyGrade" label="难度" />
          <el-table-column prop="errorMessage" label="错误信息">
            <template slot-scope="scope">
              <span class="error_message">{{ scope.row.errorMessage }}</span>
            </template>
          </el-table-column>
        </jsbos-table>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()" v-if="active == 1">取 消</el-button>
      <el-button @click="prev" v-if="active == 2">上一步</el-button>
      <el-button
        @click="next"
        type="primary"
        v-if="active < 3"
        :loading="btnLoading"
        :disabled="active == 1 && !fileName"
        >下一步
      </el-button>
      <el-button @click="cancel(true)" type="primary" v-else>关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as XLSX from "xlsx";
import {
  TemplateDownload,
  ImportData,
  ImportPreview,
} from "@/views/exam/api/question";

export default {
  name: 'ImportQuestionForm',
  data() {
    return {
      visible: false,
      btnLoading: false,
      listLoading: false,
      fileName: "",
      fileList: [],
      active: 1,
      list: [],
      resultList: [],
      result: {
        resultType: 0,
        snum: 0,
        fnum: 0,
      },
      listItems: [
        { label: "题目" },
        { label: "题目类型" },
        { label: "答案" },
        { label: "难度" },
        { label: "选项1" },
        { label: "选项2" },
        { label: "选项3" },
        { label: "选项4" },
        { label: "选项5" },
        { label: "选项6" },
        { label: "选项7" },
        { label: "选项8" },
        { label: "选项9" },
        { label: "选项10" },
        { label: "错误信息" },
      ],
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/exam/question/upload'
    };
  },
  methods: {
    prev() {
      if (this.active == 1) return;
      this.active--;
    },
    next() {
      if (this.active == 2) {
        if (!this.list.length)
          return this.$message({ message: "导入数据为空", type: "warning" });
        
        // 转换数据格式
        const submitData = this.list.map(item => ({
          ...item
        }));
        // ,
        // difficultyGradeId: this.getDifficultyGradeId(item.difficultyGrade),
        // questionType: this.getQuestionTypeId(item.questionType),
        // options: this.getOptionsArray(item)

        this.btnLoading = true;

        let folderId = '638100473177446981'; // 题库id
        let menuId = '1';
        ImportData({list: submitData}, folderId, menuId)
          .then((res) => {
            this.result = res.data;
            this.resultList = res.data.failResult;
            this.btnLoading = false;
            this.active++;
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
      if (this.active == 1) {
        if (!this.fileList.length || !this.fileName)
          return this.$message({ message: "请先上传文件", type: "warning" });
        this.btnLoading = true;
        ImportPreview({ fileName: this.fileName })
          .then((res) => {
            this.list = res.data.dataRow;
            this.btnLoading = false;
            this.active++;
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    cancel(isRefresh) {
      this.visible = false;
      if (isRefresh) {
        this.$emit("refresh");
      }
    },
    init() {
      this.active = 1;
      this.fileList = [];
      this.fileName = "";
      this.visible = true;
    },
    handleDel(index) {
      this.list.splice(index, 1);
    },
    templateDownload() {
      TemplateDownload().then((res) => {
        if (res.data && res.data.url) {
          const baseURL = process.env.VUE_APP_BASE_API || '';
          const link = document.createElement('a');
          link.href = baseURL + res.data.url;
          link.download = res.data.name || '题目导入模板.xlsx';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      });
    },
    beforeUpload(file) {
      let isRightSize = file.size / 1024 < 500;
      if (!isRightSize) this.$message.error(`文件大小不能超过500KB`);
      return isRightSize;
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    handleSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.fileList = fileList.slice(-1);
        this.fileName = res.data.name;
      } else {
        this.fileList = fileList.filter((o) => o.uid != file.uid);
        this.$message({ message: res.msg, type: "error", duration: 1000 });
      }
    },
    exportData() {
      this.$confirm("确定要导出列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.exportNewList(this.resultList);
      });
    },
    exportNewList(arr) {
      let tableData = [];
      var tabHandle = [];
      this.listItems.forEach((item) => {
        tabHandle.push(item.label);
      });
      arr.forEach((item) => {
        let rowData = [
          item.title,
          item.questionType,
          item.answer,
          item.difficultyGrade,
          item.option1 || '',
          item.option2 || '',
          item.option3 || '',
          item.option4 || '',
          item.option5 || '',
          item.option6 || '',
          item.option7 || '',
          item.option8 || '',
          item.option9 || '',
          item.option10 || '',
          item.errorMessage || '',
        ];
        tableData.push(rowData);
      });
      const arrayWithHeader = [tabHandle, ...tableData];
      var xlsxParam = { raw: true };
      let workSheet = XLSX.utils.json_to_sheet(arrayWithHeader, xlsxParam);
      let bookNew = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(bookNew, workSheet, "导出异常数据");
      let name = `题目导入异常数据_${new Date().getTime()}.xlsx`;
      XLSX.writeFile(bookNew, name);
    },
    isChoiceQuestion(type) {
      return type === '单选题' || type === '多选题';
    },
    getDifficultyGradeId(difficultyGrade) {
      const map = {
        '简单': '1',
        '中等': '2',
        '困难': '3'
      };
      return map[difficultyGrade] || '1';
    },
    getQuestionTypeId(questionType) {
      const map = {
        '判断题': '1',
        '填空题': '2',
        '单选题': '3',
        '多选题': '3',
        '问答题': '4'
      };
      return map[questionType] || '1';
    },
    getOptionsArray(item) {
      if (!this.isChoiceQuestion(item.questionType)) {
        return [];
      }

      const options = [];
      for (let i = 1; i <= 10; i++) {
        const optionKey = `option${i}`;
        if (item[optionKey]) {
          options.push({
            label: String.fromCharCode(64 + i), // A, B, C, ...
            content: item[optionKey],
            img: ''
          });
        }
      }
      return options;
    }
  },
};
</script>

<style scoped lang="scss">
.error_message {
  white-space: pre-line;
  color: #f56c6c;
}

.import-main {
  padding: 20px;
  min-height: 300px;

  .upload {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;

    .up_left {
      margin-right: 20px;
      
      img {
        width: 48px;
        height: 48px;
      }
    }

    .up_right {
      flex: 1;

      .title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 8px;
      }

      .tip {
        color: #909399;
        margin-bottom: 8px;
      }
    }
  }

  .success {
    text-align: center;
    padding: 40px 0;

    img {
      width: 64px;
      height: 64px;
      margin-bottom: 16px;
    }

    .success-title {
      font-size: 20px;
      font-weight: 500;
      margin-bottom: 8px;
    }

    .success-tip {
      color: #67c23a;
    }
  }

  .unsuccess {
    .contips {
      margin: 16px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  
  .option-item {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .option-label {
      min-width: 50px;
      color: #606266;
    }
  }
}
</style> 